<template>
	<view style="visibility: hidden;" class="canvas">
		<canvas id="updataImg" type="2d" canvas-id="updataImg" class="updataImgCanvar"></canvas>
	</view>

</template>

<script setup>
	import { getCurrentInstance, reactive, ref, defineExpose } from 'vue';
	import { pathToBase64, base64ToPath } from 'image-tools' // 图片转 base64或者互转 
	import { onLoad } from '@dcloudio/uni-app';
	import { useStore } from 'vuex';
	const { state, commit, dispatch } = useStore();
	const { proxy } = getCurrentInstance();

	let imgBoxList = reactive({
		// 设置canvas的宽高，也可以理解为压缩后图片的‘默认’最大宽高，单位px
		canvasStyle: {
			width: 500,
			height: 500
		},
		urls: [] // 输出给父组件的压缩后图片的集合
	})
	let compressImage = (path) => {
		return new Promise(async (resolve, reject) => {
			uni.getImageInfo({ //获取图片信息
				src: path,
				success(res) {
					let w = res.width,
						h = res.height,
						scale = w / h;
					w = 960 || w
					h = w / scale
					const query = uni.createSelectorQuery().in(proxy);
					let canvas = query.select('#updataImg').fields({ node: true, size: true })
					canvas.exec(async (res) => {
						const cvs = res[0].node
						cvs.width = w
						cvs.height = h
						let ctx = cvs.getContext('2d');
						const img = cvs.createImage()
						await new Promise(resolve => {
							img.onload = resolve
							img.src = path
						})
						ctx.drawImage(img, 0, 0, w, h);
						let base64 = cvs.toDataURL('image/jpg', 0.1);
						console.log(base64, 'base64-------')
						base64ToPath(base64)
							.then(res => {
								resolve(res);
							})
							.catch(error => {
								console.error(error)
							})

					})

				},
				fail(err) {
					console.log(err)
					reject(err)
				}
			})

		})
	}





	defineExpose({ compressImage })
</script>

<style scoped lang="scss">
	.canvas {
		position: fixed;
		left: -100vw;
		top: -100vh;
	}
</style>